package com.zsy.oauth2.config;

import com.zsy.oauth2.config.dto.CustomUser;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName CustomTokenEnhancer
 * @Description 在访问令牌被存储之前对其进行增强
 * @Author zhaoshouyun
 * @Date 2020/4/20 20:35
 * @Version 1.0
 */
@Configuration
public class CustomTokenEnhancer  implements TokenEnhancer {

    /** 进行外围用户信息进行增强，是和token一起返回的，其实这个方法没必要用了，因为，我们已经封装到token里，看项目需要是否添加外围信息
     * @Description
     * @Author zhaoshouyun
     * @Date 20:54 2020/4/20
     * @Param [accessToken, authentication]
     * @return org.springframework.security.oauth2.common.OAuth2AccessToken
     **/
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        Object obj =  authentication.getPrincipal();

        if (obj instanceof CustomUser){
            final Map<String, Object> additionalInfo = new HashMap<>();
            //暂时注释掉外围用户信息
          /*  CustomUser customUser = (CustomUser)obj;
            additionalInfo.put("userId", customUser.getId());
            additionalInfo.put("name", customUser.getName());
            additionalInfo.put("otherUserInfoValue",customUser.getOtherUserInfoParam());*/
            // 注意添加的额外信息，最好不要和已有的json对象中的key重名，容易出现错误
            //additionalInfo.put("authorities", user.getAuthorities());
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
        }

        return accessToken;
    }
}
